package com.fengyuncx.influency.phone_verify_plugin;


import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.mobile.auth.gatewayauth.AuthUIConfig;
import com.mobile.auth.gatewayauth.AuthUIControlClickListener;
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper;
import com.mobile.auth.gatewayauth.PreLoginResultListener;
import com.mobile.auth.gatewayauth.ResultCode;
import com.mobile.auth.gatewayauth.TokenResultListener;
import com.mobile.auth.gatewayauth.model.TokenRet;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.SoftReference;
import java.util.HashMap;

import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.JSONMessageCodec;
import io.flutter.plugin.common.JSONMethodCodec;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.view.FlutterNativeView;

public class PhoneNumVerifyHandler implements MethodChannel.MethodCallHandler, PluginRegistry.ViewDestroyListener {
    private static final String TAG = PhoneNumVerifyHandler.class.getSimpleName();
    public static final String CHANNEL = "gitee.com/influency/phone_verify_plugin";

    private Context mApplicationContext;
    private Activity mActivity;
    private MethodChannel mChannel;

    private String authKey;
    private PhoneNumberAuthHelper mPhoneNumberAuthHelper;
    private TokenResultListener mTokenListener;

    private String phoneNum;

    public PhoneNumVerifyHandler() {
    }

    public void setApplicationContext(Context applicationContext) {
        this.mApplicationContext = applicationContext;
    }

    public void setActivity(Activity activity) {
        this.mActivity = activity;
    }

    public PhoneNumVerifyHandler(Context context, Activity activity) {
        this.mApplicationContext = context;
        this.mActivity = activity;
    }

    public void startListening(BinaryMessenger binaryMessenger) {
        mChannel = new MethodChannel(binaryMessenger, CHANNEL, JSONMethodCodec.INSTANCE);
        mChannel.setMethodCallHandler(this);
    }

    public void stopListening() {
        if (mChannel != null) {
            mChannel.setMethodCallHandler(null);
            mChannel = null;
        }
//        if (register.compareAndSet(true, false)) {
//            WechatReceiver.unregisterReceiver(applicationContext, wechatReceiver);
//        }
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
        switch (call.method) {
            case ArgumentStaticMap.METHOD_INIT_SDK:
                handleInitSdk(call);
                result.success(null);
                break;
            case ArgumentStaticMap.METHOD_CHECK_ENV:
                mPhoneNumberAuthHelper.checkEnvAvailable(PhoneNumberAuthHelper.SERVICE_TYPE_LOGIN);
                accelerateLoginPage(5000);
                result.success(null);
                break;
            case ArgumentStaticMap.METHOD_SET_PRIVACY:
                handlePrivacyData(call);
                result.success(null);
                break;
            case ArgumentStaticMap.METHOD_LOGIN:
                handleLogin(result);
                result.success(null);
                break;
            case ArgumentStaticMap.INVOKE_METHOD_QUIT_LOGIN:
                mPhoneNumberAuthHelper.hideLoginLoading();
                mPhoneNumberAuthHelper.quitLoginPage();
                mPhoneNumberAuthHelper.setAuthListener(null);
                result.success(null);
                break;
            default:
                result.notImplemented();
                break;
        }


    }

    /**
     *
     * 设置协议显示内容
     * 设置UI
     * @param call
     */
    private void handlePrivacyData(MethodCall call) {
        String privacyName = call.argument(ArgumentStaticMap.PARAM_PRIVACY_ISSUE_NAME);
        String userIssueName = call.argument(ArgumentStaticMap.PARAM_USER_ISSUE_NAME);
        String privacyUrl = call.argument(ArgumentStaticMap.PARAM_PRIVACY_ISSUE_URL);
        String userIssueUrl = call.argument(ArgumentStaticMap.PARAM_USER_ISSUE_URL);
        if (TextUtils.isEmpty(authKey)) {
            LogUtil.logW(TAG, "authKey null");
        } else {
            LogUtil.logW(TAG, "authKey found success");
        }

        //设置协议
        if (userIssueName != null && userIssueUrl != null) {
            authUIConfigBuilder.setAppPrivacyOne(userIssueName, userIssueUrl);
        }
        if (privacyName != null && privacyUrl != null) {
            authUIConfigBuilder.setAppPrivacyTwo(privacyName, privacyUrl);
        }
        authUIConfigBuilder.setVendorPrivacyPrefix("《");
        authUIConfigBuilder.setVendorPrivacySuffix("》");
        authUIConfigBuilder.setPrivacyState(true);

        //设置导航栏
        authUIConfigBuilder.setNavColor(Color.WHITE);
//        authUIConfigBuilder.setNavColor(0xFFFF7043);
        authUIConfigBuilder.setNavText("风韵出行");
        authUIConfigBuilder.setNavTextColor(Color.argb(0xff, 0x33, 0x33, 0x33));
        authUIConfigBuilder.setNavTextSizeDp(22);
        if (mActivity != null) {
            authUIConfigBuilder.setNavReturnImgDrawable(mActivity.getResources().getDrawable(R.drawable.ic_arrow_back));
        } else {
            authUIConfigBuilder.setNavReturnImgPath("ic_arrow_back");
        }
        authUIConfigBuilder.setNavReturnHidden(false);

        //设置状态栏
        authUIConfigBuilder.setStatusBarColor(Color.WHITE);
        authUIConfigBuilder.setLightColor(true);
        authUIConfigBuilder.setWebViewStatusBarColor(Color.WHITE);
        authUIConfigBuilder.setWebNavColor(Color.WHITE);
        authUIConfigBuilder.setWebNavTextColor(Color.argb(0xff, 0x33, 0x33, 0x33));

        //设置登陆按钮
        authUIConfigBuilder.setLogBtnTextSizeDp(20);
        if (mActivity != null) {
            authUIConfigBuilder.setLogBtnBackgroundDrawable(mActivity.getResources().getDrawable(R.drawable.drawable_btn_login));
        } else {
            authUIConfigBuilder.setLogBtnBackgroundPath("drawable_btn_login");
        }

        //设置logo
        if (mActivity != null) {
            authUIConfigBuilder.setLogoImgDrawable(mActivity.getResources().getDrawable(R.mipmap.logo));
        } else {
            authUIConfigBuilder.setLogBtnBackgroundPath("logo");
        }
        if (mActivity != null) {
            authUIConfigBuilder.setPageBackgroundDrawable(mActivity.getResources().getDrawable(R.drawable.drawable_bg));
        } else {
            authUIConfigBuilder.setPageBackgroundPath("drawable_bg");
        }
        authUIConfigBuilder.setLogoWidth(100);
        authUIConfigBuilder.setLogoHeight(100);
    }


    private void handleLogin(MethodChannel.Result result) {
        mPhoneNumberAuthHelper.setAuthUIConfig(authUIConfigBuilder.create());
        mPhoneNumberAuthHelper.getLoginToken(mApplicationContext, 5000);
    }


    private void handleInitSdk(MethodCall call) {
        authKey = call.argument(ArgumentStaticMap.PARAM_AUTH_KEY);
        authUIConfigBuilder = new AuthUIConfig.Builder();
        initVerifyPhoneHelper();
//        accelerateVerify(5000);
        mPhoneNumberAuthHelper.setUIClickListener(new AuthUIControlClickListener() {
            @Override
            public void onClick(String code, Context context, String json) {
                LogUtil.logE(TAG, "code = " + code);
                LogUtil.logE(TAG, "json = " + json);

                if (mChannel == null) {
                    return;
                }
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("code", code);
                    jsonObject.put("json", json);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                mChannel.invokeMethod(ArgumentStaticMap.INVOKE_METHOD_ON_CLICK, jsonObject);
            }
        });
    }

    private void initVerifyPhoneHelper() {
        mTokenListener = new TokenResultListener() {

            @Override
            public void onTokenSuccess(String s) {
                LogUtil.logD(TAG, "onTokenSuccess：s =" + s);
                try {
                    TokenRet pTokenRet = TokenRet.fromJson(s);
                    if (!ResultCode.CODE_SUCCESS.equals(pTokenRet.getCode())) {
                        return;
                    }
                    String token = pTokenRet.getToken();
                    LogUtil.logD(TAG, "获取token成功：" + token);
                    if (mChannel != null) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("code", pTokenRet.getCode());
                        jsonObject.put("token", token);
                        jsonObject.put("message", "获取token成功");
                        mChannel.invokeMethod(ArgumentStaticMap.INVOKE_METHOD_LOGIN_TOKEN, jsonObject);
                    }
//                    TokenRet pTokenRet = TokenRet.fromJson(s);
//                    if (!TextUtils.isEmpty(phoneNum)&&ResultCode.CODE_SUCCESS.equals(pTokenRet.getCode()) && !TextUtils.isEmpty(pTokenRet.getToken())) {
//                        getResultWithToken(pTokenRet.getToken(), phoneNum);
//                    }
//                    mPhoneNumberAuthHelper.setAuthListener(null);
//                    result.success(null);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onTokenFailed(final String s) {
                LogUtil.logE(TAG, "获取token失败：" + s);
                TokenRet pTokenRet = TokenRet.fromJson(s);
                if (pTokenRet == null||!ResultCode.CODE_GET_TOKEN_FAIL.equals(pTokenRet.getCode())) {
                    return;
                }
                try {
                    if (mChannel != null) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("code", pTokenRet.getCode());
                        jsonObject.put("message", "获取token失败");
                        mChannel.invokeMethod(ArgumentStaticMap.INVOKE_METHOD_LOGIN_TOKEN, jsonObject);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mPhoneNumberAuthHelper.setAuthListener(null);


//                result.error("-9999", "get token failed", null);
            }
        };
        mPhoneNumberAuthHelper = PhoneNumberAuthHelper.getInstance(mApplicationContext, mTokenListener);
        mPhoneNumberAuthHelper.setAuthSDKInfo(authKey);

    }


    private AuthUIConfig.Builder authUIConfigBuilder;

    /**
     * 加速校验
     * 进入输入手机号页面调用此接口，用户输入完手机号点击确定可以更快的获取token
     *
     * @param timeout
     */
    public void accelerateVerify(int timeout) {
        mPhoneNumberAuthHelper.accelerateVerify(timeout, new PreLoginResultListener() {
            @Override
            public void onTokenSuccess(String vendor) {
                if(mActivity!=null){
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            LogUtil.logE(TAG, "accelerateVerify：" + vendor );
                            try {
                                if (mChannel != null) {
                                    JSONObject jsonObject = new JSONObject();
                                    jsonObject.put("code", "500000");
                                    jsonObject.put("ISP", vendor);//unknown
                                    jsonObject.put("message", "获取运营商成功");//unknown
                                    mChannel.invokeMethod(ArgumentStaticMap.INVOKE_METHOD_ISP, jsonObject);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            String ISPName;
                            switch (vendor) {
                                case "CUCC":
                                    ISPName = "中国联通";
                                    break;
                                case "CTCC":
                                    ISPName = "中国电信";
                                    break;
                                case "CMCC":
                                    ISPName = "中国移动";
                                    break;
                                default:
                                    ISPName = "网络供应商";
                                    break;
                            }
                            authUIConfigBuilder.setSloganText("认证服务由" + ISPName + "提供");
                            mPhoneNumberAuthHelper.setAuthUIConfig(authUIConfigBuilder.create());
                            //成功时返回运营商简称  eg:CUCC
                        }
                    });
                }

            }

            @Override
            public void onTokenFailed(String vendor, String errorMsg) {
                LogUtil.logE(TAG, "accelerateVerify：" + vendor + "， " + errorMsg);
                if (mChannel != null) {
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("code", "500001");
                        jsonObject.put("ISP", "unknown");//unknown
                        jsonObject.put("message", "获取运营商失败");//unknown
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    mChannel.invokeMethod(ArgumentStaticMap.INVOKE_METHOD_ISP, jsonObject);
                }
            }
        });
    }
    /**
     * 检测环境是否可以使用一键登陆
     * 加速授权⻚唤起
     *
     * @param timeout
     */
    public void accelerateLoginPage(int timeout) {
        mPhoneNumberAuthHelper.accelerateLoginPage(timeout, new PreLoginResultListener() {
            @Override
            public void onTokenSuccess(String vendor) {
                if(mActivity!=null){
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            LogUtil.logE(TAG, "accelerateLoginPage：" + vendor );
                            try {
                                if (mChannel != null) {
                                    JSONObject jsonObject = new JSONObject();
                                    jsonObject.put("code", "500000");
                                    jsonObject.put("ISP", vendor);//unknown
                                    jsonObject.put("message", "获取运营商成功");//unknown
                                    mChannel.invokeMethod(ArgumentStaticMap.INVOKE_METHOD_ISP, jsonObject);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            String ISPName;
                            switch (vendor) {
                                case "CUCC":
                                    ISPName = "中国联通";
                                    break;
                                case "CTCC":
                                    ISPName = "中国电信";
                                    break;
                                case "CMCC":
                                    ISPName = "中国移动";
                                    break;
                                default:
                                    ISPName = "网络供应商";
                                    break;
                            }
                            authUIConfigBuilder.setSloganText("认证服务由" + ISPName + "提供");
                            mPhoneNumberAuthHelper.setAuthUIConfig(authUIConfigBuilder.create());
                            //成功时返回运营商简称  eg:CUCC
                        }
                    });
                }

            }

            @Override
            public void onTokenFailed(String vendor, String errorMsg) {
                LogUtil.logE(TAG, "accelerateLoginPage：" + vendor + "， " + errorMsg);
                if (mChannel != null) {
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("code", "500001");
                        jsonObject.put("ISP", "unknown");//unknown
                        jsonObject.put("message", "获取运营商失败");//unknown
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    mChannel.invokeMethod(ArgumentStaticMap.INVOKE_METHOD_ISP, jsonObject);
                }
            }
        });
    }

    /// --- view destroy
    @Override
    public boolean onViewDestroy(FlutterNativeView view) {
        return false;
    }
}
